import { login as loginApi, getUserInfo } from '@/api/user'
import { getToken, setToken, clearToken } from '@/utils/auth'
import { constantRoute } from '@/router/routes'

export default {
  namespaced: true,
  state: {
    username: '',
    token: getToken(),
    menuRoutes: constantRoute,
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
    },

    RESET_TOKEN(state) {
      state.token = ''
    },

    RESET_NAME(state) {
      state.username = ''
    },

    SET_NAME(state, username) {
      state.username = username
    },
  },
  actions: {
    async login({ commit }, userInfo) {
      const res = await loginApi(userInfo)
      let token = res.data.token
      setToken(token)
      commit('SET_TOKEN', token)
    },

    async getInfo({ commit }) {
      const res = await getUserInfo()
      commit('SET_NAME', res.data.nickname)
    },

    logout({ commit }) {
      commit('RESET_NAME')
      commit('RESET_TOKEN')
      clearToken()
    },
  },
}
